package com.ck.shardingspheremaster.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @Author yd
 * @Date 2019/1/3 21:10
 */
@Slf4j
public class MyShardingConfig implements PreciseShardingAlgorithm {

    /**
     * 精确分片算法
     * sex，如果小于等于5，数据对应的表为：t_user0
     * sex，如果大于5，数据对应的表为：t_user1
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {

            log.info("【精确分片算法】：[availableTargetNames]:{},[shardingValue]:{}",availableTargetNames,shardingValue);

            //TODO 重构
            if(shardingValue.getColumnName().equalsIgnoreCase("city_id")){
                Comparable value = shardingValue.getValue();
                int i = value.compareTo(5);
                int suffix = -1;
                if(i<=0){
                    suffix = 0;
                }else{
                    suffix = 1;
                }
                //String s = ("t_user" + suffix);
                String s = ("ds" + suffix);
                log.info("【精确分片算法路由结果】：{}",s);
                return s;
            }
            return null;
    }





}
